using MediatR;
using Microsoft.AspNetCore.Mvc;
using WMS.Domain;
using WMS.ErrorCode;
using WMS.Infrasturcture.Interfaces;
using WMS.WebApiRead.Application.Command;
using WMS.WebApiRead.DTO;

namespace WMS.WebApiRead.Controllers
{
    /// <summary>
    /// 产品信息读操作控制器（查询）
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly ILogger<ProductController> logger;
        private readonly IBaseRepository<ProductInfo> productRepository;

        /// <summary>
        /// 构造函数，注入MediatR、日志服务和仓储
        /// </summary>
        public ProductController(
            IMediator mediator,
            ILogger<ProductController> logger,
            IBaseRepository<ProductInfo> productRepository)
        {
            this.mediator = mediator;
            this.logger = logger;
            this.productRepository = productRepository;
        }

        /// <summary>
        /// 分页查询产品信息（支持条件筛选、联表查询）
        /// </summary>
        /// <param name="queryDTO">查询参数</param>
        /// <returns>返回分页结果</returns>
        [HttpGet]
        public async Task<ApiResult<ApiPaging<List<ProductInfoResultDTO>>>> QueryProduct([FromQuery] ProductQueryDTO queryDTO)
        {
            logger.LogInformation($"开始查询产品信息，页码：{queryDTO.PageIndex}，每页大小：{queryDTO.PageSize}");

            return await mediator.Send(new ProductQueryCommand
            {
                QueryDTO = queryDTO
            });
        }

        /// <summary>
        /// 根据产品ID查询产品详情
        /// </summary>
        /// <param name="productId">产品ID</param>
        /// <returns>返回产品详情</returns>
        [HttpGet]
        public async Task<ApiResult<ProductInfoResultDTO>> GetProductById([FromQuery] int productId)
        {
            logger.LogInformation($"开始查询产品详情，产品ID：{productId}");

            try
            {
                var product = productRepository.GetAll()
                    .Where(x => x.ProductId == productId && !x.IsDeleted)
                    .Select(x => new ProductInfoResultDTO
                    {
                        ProductId = x.ProductId,
                        ProductCode = x.ProductCode,
                        ProductName = x.ProductName,
                        SpecificationModel = x.SpecificationModel,
                        Unit = x.Unit,
                        InboundUnitPrice = x.InboundUnitPrice,
                        CurrentInventory = x.CurrentInventory,
                        WarehouseId = x.WarehouseId,
                        IsDeleted = x.IsDeleted,
                        DataStatus = x.DataStatus,
                        CreateName = x.CreateName,
                        CreateTime = x.CreateTime,
                        UpdateName = x.UpdateName,
                        UpdateTime = x.UpdateTime
                    })
                    .FirstOrDefault();

                if (product == null)
                {
                    return new ApiResult<ProductInfoResultDTO>
                    {
                        Code = ApiResultEnum.查询失败,
                        Message = "产品信息不存在",
                        Data = null
                    };
                }

                return new ApiResult<ProductInfoResultDTO>
                {
                    Code = ApiResultEnum.查询成功,
                    Message = "查询产品详情成功",
                    Data = product
                };
            }
            catch (Exception ex)
            {
                logger.LogError($"查询产品详情异常：{ex.Message}");
                return new ApiResult<ProductInfoResultDTO>
                {
                    Code = ApiResultEnum.查询失败,
                    Message = $"查询产品详情异常：{ex.Message}",
                    Data = null
                };
            }
        }

        /// <summary>
        /// 获取所有产品单位列表（用于下拉选择框）
        /// </summary>
        /// <returns>返回单位列表（去重）</returns>
        [HttpGet]
        public async Task<ApiResult<List<string>>> GetProductUnitList()
        {
            logger.LogInformation("开始查询产品单位列表");

            try
            {
                // 查询所有未删除的产品，获取不重复的单位列表
                var units = productRepository.GetAll()
                    .Where(x => !x.IsDeleted && !string.IsNullOrWhiteSpace(x.Unit))
                    .Select(x => x.Unit)
                    .Distinct() // 去重
                    .OrderBy(x => x) // 按字母排序
                    .ToList();

                return new ApiResult<List<string>>
                {
                    Code = ApiResultEnum.查询成功,
                    Message = "查询产品单位列表成功",
                    Data = units
                };
            }
            catch (Exception ex)
            {
                logger.LogError($"查询产品单位列表异常：{ex.Message}");
                return new ApiResult<List<string>>
                {
                    Code = ApiResultEnum.查询失败,
                    Message = $"查询产品单位列表异常：{ex.Message}",
                    Data = new List<string>()
                };
            }
        }
    }
}

